package com.ly.gen.utils;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.ly.common.core.config.properties.GenProperties;
import com.ly.common.core.exception.ServiceException;
import com.ly.gen.entity.GenTable;
import freemarker.cache.FileTemplateLoader;
import freemarker.cache.MultiTemplateLoader;
import freemarker.core.TemplateClassResolver;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 代码生成工具类
 *
 * @author luoyun
 * @Date: 2025/6/13 13:52
 * @Note:
 */
@Slf4j
public class GenUtils {

    /**
     * 获取Configuration-freemark
     *
     * @param files
     * @return
     * @throws IOException
     */
    public static Configuration getConfiguration(File[] files) {
        Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        FileTemplateLoader[] loaderList = new FileTemplateLoader[files.length];
        for (int i = 0; i < files.length; ++i) {
            File var6 = files[i];
            try {
                loaderList[i] = new FileTemplateLoader(var6);
            } catch (IOException e) {
                throw new ServiceException("代码生成错误，配置FileTemplateLoader失败");
            }
        }
        MultiTemplateLoader var7 = new MultiTemplateLoader(loaderList);
        cfg.setTemplateLoader(var7);
        cfg.setNewBuiltinClassResolver(TemplateClassResolver.SAFER_RESOLVER);
        cfg.setNumberFormat("###############");
        cfg.setBooleanFormat("true,false");
        // cfg.setDefaultEncoding("UTF-8");
        return cfg;
    }

    /**
     * 原始参数
     * @return
     */
    public static Map<String, Object> getParams() {
        HashMap var1 = new HashMap();
        var1.put("bussiPackage", "com.ly");
        var1.put("entityPackage", "online11111");
        var1.put("entityPackagePath", "online11111".replace(".", "/"));
        var1.put("entityName", "TestPerson");
        var1.put("tableName", "test_person");
        var1.put("primaryKeyField", "id");
        var1.put("primaryKeyPolicy", "java.lang.String");
        var1.put("columns", "List<ColumnVo>");
        var1.put("tableVo", "TableVo");
        var1.put("originalColumns", "List<ColumnVo>");
        return var1;
    }

    /**
     * 生成文件
     */
    public static String getFreemarkerFile(File file, GenTable table, GenProperties genProperties, Map<String, Object> paramsMap, Configuration configuration) {
        // E:\02-temp\代码生成\src\main + \java\com\ly\base\controller\TestPersonController.java
        String resultFilePath = genProperties.getProjectPath() + "\\src\\main";
        log.debug("代码生成目录为：{}", resultFilePath);     // E:\02-temp\代码生成\src\main
        String filePath = file.getAbsolutePath();
        String templatePath = StrUtil.subAfter(filePath, "default", true);
        String handleTemplatePath = StrUtil.replace(templatePath, "\\", "/");
        log.debug("当前模版路径为：{}", handleTemplatePath);           // "one/java/${bussiPackage}/${entityPackage}/entity/${entityName}.javai";
        String realPath = getRealPath(templatePath,table);
        log.debug("文件生成：相对真实路径为：{}", realPath);       //\java\com\ly\base\controller\TestPersonController.java
        String finalPath = resultFilePath + realPath;
        //StrUtil.replace(resultFilePath + realPath, "\\", "\\\\");
        log.debug("文件生成：最终路径为：{}", finalPath);        // E:\02-temp\代码生成\src\main\java\com\ly\base\controller\TestPersonController.java
        try {
            Template template = configuration.getTemplate(handleTemplatePath);
            File parentDir = new File(finalPath).getParentFile();
            // 检查并创建父目录
            if (parentDir != null && !parentDir.exists()) {
                boolean dirsCreated = parentDir.mkdirs(); // 递归创建所有不存在的目录
                if (!dirsCreated) {
                    throw new ServiceException("代码生成报错：无法创建父目录");
                }
            }

            // BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(finalPath), "UTF-8"));
            // bufferedWriter.close();
            FileWriter fileWriter = new FileWriter(finalPath);
            template.process(paramsMap, fileWriter);
            fileWriter.close();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("代码生成报错: {}", e.getMessage());
            throw new ServiceException("代码生成报错");
        }
        log.info("文件生成成功： => {}", finalPath);
        return finalPath;
    }

    public static String getRealPath(String templatePath,GenTable table){
        return templatePath
                .replace("${bussiPackage}", table.getBussiPackage().replace(".", File.separator))
                .replace("${entityPackage}", table.getEntityPackage())
                .replace("${entityName}", table.getEntityName())
                .replace("${currentDate}", DateUtil.format(new Date(), DatePattern.PURE_DATETIME_PATTERN))
                .replace(".javai", ".java")
                .replace(".vuei", ".vue")
                .replace(".tsi", ".ts");
    }
}
